package com.star.robot.controller;

import com.star.robot.dto.*;
import com.star.robot.entity.Admin;
import com.star.robot.entity.DtArea;
import com.star.robot.entity.Team;
import com.star.robot.entity.TeamScore;
import com.star.robot.enums.AdminTypeEnum;
import com.star.robot.enums.CompanyTypeEnum;
import com.star.robot.enums.ProjectClassEnum;
import com.star.robot.enums.ProjectLevelEnum;
import com.star.robot.repository.DtAreaRepositoty;
import com.star.robot.repository.TeamRepository;
import com.star.robot.repository.TeamScoreRepository;
import com.star.robot.service.AdminService;
import com.star.robot.util.DtAreaUtil;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/team/score")
@Slf4j
public class TeamScoreController {

    @Autowired
    private TeamScoreRepository teamScoreRepository;


    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private DtAreaRepositoty dtAreaRepositoty;

    @Autowired
    private AdminService adminService;
    
    @Autowired
    private DtAreaUtil dtAreaUtil;


    /**
     * 根据teamid查询成绩详情
     * @return
     */
    @GetMapping(value = "/teamId")
    public ResultDto teamId(TeamMemberQueryDto teamMemberQueryDto){
        List<TeamScore> teamScoreList = teamScoreRepository.findByTeam_Id(teamMemberQueryDto.getTeamId());

        if(!CollectionUtils.isEmpty(teamScoreList)){
            for(TeamScore teamScore : teamScoreList){
                teamScore.setTeam(null);
            }
        }
        return ResultDto.builder()
                .data(teamScoreList)
                .build();

    }

    /**
     *
     * @param requestDto
     * @return
     */
    @GetMapping(value = "/")
    @ApiOperation(value = "队伍成绩查询",notes = "队伍成绩查询")
    public PageResultDto getBackend(TeamBackendQueryDto requestDto , HttpServletRequest request){
        PageResultDto<Team> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());

            Page<Team> pageable = teamRepository.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
                List<Predicate> conditions = new ArrayList<>();
                    //权限
                    AdminTypeEnum adminTypeEnum = adminService.getCurrentAdminLevel(request);
                    log.info("成绩管理查询　：　参数[adminTypeEnum] :"+adminTypeEnum.getName());
                    if(adminTypeEnum == AdminTypeEnum.PROVINCEADMIN){
                        Predicate adminTypeCond = cb.equal(root.get("project").get("projectLevelEnum") , ProjectLevelEnum.PROVINCELEVEL);
                        conditions.add(adminTypeCond);
                    }else{
                        Predicate adminTypeCond = cb.equal(root.get("project").get("projectLevelEnum") , ProjectLevelEnum.PROVINCELEVEL);
                        conditions.add(adminTypeCond);

                        //市
                        Long cityId = adminService.getCurrentAdminCityId(request);
                        log.info("成绩管理查询　：　参数[cityId] :"+cityId);
                        if(cityId != null){
                            Predicate cityCondition = cb.equal(root.get("company").get("cityId")  , cityId);
                            conditions.add(cityCondition);
                        }
                    }
                //项目
                if(requestDto.getProjectId() != null){
                    Predicate projectCond = cb.equal(root.get("project").get("id") , requestDto.getProjectId());
                    conditions.add(projectCond);
                }
                //单位名称
                    if(!StringUtils.isEmpty(requestDto.getCompanyName())){
                    Predicate companyCond = cb.like(root.get("company").get("name") , "%"+requestDto.getCompanyName()+"%");
                    conditions.add(companyCond);
                }

                //省
//                    if(requestDto.getProvinceId() != null){
//                        Predicate provinceCondition = cb.equal(root.get("provinceId")  , requestDto.getProvinceId());
//                        conditions.add(provinceCondition);
//                    }
                //市
                    if(requestDto.getCityId() != null){
                    Predicate cityCondition = cb.equal(root.get("company").get("cityId")  , requestDto.getCityId());
                    conditions.add(cityCondition);
                }
                //区
//                    if(requestDto.getAreaId() != null){
//                        Predicate areaCondition = cb.equal(root.get("areaId")  , requestDto.getAreaId());
//                        conditions.add(areaCondition);
//                    }
                //队员姓名
                    if(!StringUtils.isEmpty(requestDto.getTeamMemberName())){
                    Predicate memberNameCond = cb.like(root.get("teamMembers").get("name")  , "%"+requestDto.getTeamMemberName()+"%");
                    conditions.add(memberNameCond);
                }
                //队员身份证
                    if(!StringUtils.isEmpty(requestDto.getTeamMemberIdCard())){
                    Predicate memberIdCardCond = cb.like(root.get("teamMembers").get("idCard")  , "%"+requestDto.getTeamMemberName()+"%");
                    conditions.add(memberIdCardCond);
                }
                //队员衣服尺码
                    if(!StringUtils.isEmpty(requestDto.getTeamMemberIdCard())){
                    Predicate memberIdCardCond = cb.equal(root.get("teamMembers").get("clotherSizeEnum")  , requestDto.getClotherSizeEnum());
                    conditions.add(memberIdCardCond);
                }

                //队伍名称
                    if(!StringUtils.isEmpty(requestDto.getTeamName())){
                    Predicate teamNameCond = cb.like(root.get("teamName") , "%"+requestDto.getTeamName()+"%");
                    conditions.add(teamNameCond);
                }
                //单位性质
                    if(requestDto.getCompanyType() !=null){
                    CompanyTypeEnum companyType = null;
                    if(requestDto.getCompanyType().intValue() == 1){
                        companyType =  CompanyTypeEnum.XUEXIAO;
                    }else if(requestDto.getCompanyType().intValue() == 2){
                        companyType =  CompanyTypeEnum.JIGOU;
                    }else{
                        //默认学校
                        companyType =  CompanyTypeEnum.XUEXIAO;
                    }
                    Predicate companyTypeCond = cb.equal(root.get("company").get("companyType") ,companyType);
                    conditions.add(companyTypeCond);

                }
                //项目名称
                    if(!StringUtils.isEmpty(requestDto.getProjectName())){
                    Predicate baoMingDateCond = cb.like(root.get("project").get("name") ,"%"+requestDto.getProjectName() + "%");
                    conditions.add(baoMingDateCond);
                }
                //成绩 TODO 业务待确认

                //报名时间 => 队伍　新增时间
                    if(!StringUtils.isEmpty(requestDto.getBaoMingDateStart())
                            && !StringUtils.isEmpty(requestDto.getBaoMingDateEnd())){
                    Predicate baoMingDateCond = cb.between(root.get("createTime") ,requestDto.getBaoMingDateStart() , requestDto.getBaoMingDateEnd());
                    conditions.add(baoMingDateCond);
                }

                //组别
                    if(requestDto.getGroupType() != null){
                        ProjectClassEnum groupTypeEnum = null;
                    if(requestDto.getGroupType() == 1){
                        groupTypeEnum = ProjectClassEnum.XIAOXUE;
                    }else if(requestDto.getGroupType() == 2){
                        groupTypeEnum = ProjectClassEnum.CHUZHONG;
                    }else if(requestDto.getGroupType() == 3){
                        groupTypeEnum = ProjectClassEnum.GAOZHONG;
                    }else{
                        //默认小学组
                        groupTypeEnum = ProjectClassEnum.XIAOXUE;
                    }
                    Predicate groupTypeCond = cb.equal(root.get("projectClassEnum") ,groupTypeEnum);
                    conditions.add(groupTypeCond);
                }

                Predicate[] pre = new Predicate[conditions.size()];

                    cq.where(conditions.toArray(pre));
                    return cq.getRestriction();
                }
            } , page);

            List<TeamRespDto> teamRespDtos = new ArrayList<>();
            if(	!CollectionUtils.isEmpty(pageable.getContent()) ) {
                for(Team team :pageable.getContent()) {
                    String areaName = null;
                    String cityName = null;
                    String areaString = "";
                    if (!StringUtils.isEmpty(team.getCompany().getProvinceId())) {
                    	areaString += dtAreaUtil.getAreaName(Long.valueOf(team.getCompany().getProvinceId()));
    				}              
                    if (!StringUtils.isEmpty(team.getCompany().getCityId())) {
                    	if (areaString.length()>0) {
                    		areaString += "-";
    					}
                    	areaString += dtAreaUtil.getAreaName(Long.valueOf(team.getCompany().getCityId()));
    				}    
                    if (!StringUtils.isEmpty(team.getCompany().getAreaId())) {
                    	if (areaString.length()>0) {
                    		areaString += "-";
    					}
                    	areaString += dtAreaUtil.getAreaName(Long.valueOf(team.getCompany().getAreaId()));
    				}
                    if(team.getCompany().getAreaId() != null ){
                        DtArea area = dtAreaRepositoty.findById(Long.valueOf(team.getCompany().getAreaId())).get();
                        DtArea city = dtAreaRepositoty.findById(Long.valueOf(team.getCompany().getCityId())).get();
                        areaName = area != null ? area.getAreaName() : null;
                        cityName = city != null ? city.getAreaName() : null;
                    }

                    Double scoreSum = teamScoreRepository.selectScoreSum(team.getId());
                    TeamRespDto teamRespDto = TeamRespDto.builder()
                            .projectName(team.getProject() != null ? team.getProject().getName() : null)
                            .areaName(areaName)
                            .cityName(cityName)
                            .companyType(team.getCompany().getCompanyType().getName())
                            .companyName(team.getCompany().getName())
                            .teamName(team.getTeamName())
                            .teamType(team.getProjectClassEnum().getName())
                            .teamScoreSum(scoreSum)
                            .teamId(team.getId())
                            .memberCount(team.getTeamMembers().size())
                            .leaderCount(team.getTeamLeaders().size())
                            .location(areaString)
                            .build();
                    teamRespDtos.add(teamRespDto);
                }
            }

            Page pagedTeamMembers = new PageImpl(teamRespDtos , page ,pageable.getTotalElements() );
            results.setCount(pagedTeamMembers.getTotalElements());
            results.setData(pagedTeamMembers.getContent());

            return results;
        }
        return PageResultDto.builder().data(null).build();

    }

    /**
     * 发布成绩
     * @return
     */
    @RequestMapping("/publish")
    public ResultDto publish(){
        teamScoreRepository.updateSatus(true);
        return ResultDto.builder().data(null).success(true).message("发布成功").build();
    }


}
